#coding:utf-8
from lovewith.account.models import MtUserMessage


class NoticeApi:
    def __init__(self):
        #分页显示数量
        self.page_size = 8

    @staticmethod
    def check_data(notice_id, user_id):
        notice_filter_data = MtUserMessage.objects.filter(id=int(notice_id), receiver_id=int(user_id))
        if notice_filter_data.exists():
            return notice_filter_data[0]

        return None

    #获取用户通知总数
    @staticmethod
    def get_count_by_user(user_id, notice_type='all'):
        if notice_type == 'unread':
            return MtUserMessage.objects.filter(receiver_id=int(user_id), has_read=0).count()
        else:
            return MtUserMessage.objects.filter(receiver_id=int(user_id)).count()

    #发送通知
    @staticmethod
    def send(**kwargs):
        new_notice = MtUserMessage(**kwargs)
        new_notice.save()

    #获取分页通知数
    def get_by_page(self, user_id, page_no=1, notice_type='all'):
        total = self.get_count_by_user(user_id)
        start = (page_no - 1) * self.page_size
        last = page_no * self.page_size

        if last > total:
            last = total

        if notice_type == 'unread':
            return MtUserMessage.objects.filter(receiver_id=int(user_id), has_read=0).order_by('-id')[start:last]
        else:
            return MtUserMessage.objects.filter(receiver_id=int(user_id)).order_by('-id')[start:last]

    #获取未读通知数量
    @staticmethod
    def get_unread_count_by_user(user_id):
        return MtUserMessage.objects.filter(has_read=0, receiver_id=int(user_id)).count()

    #获取通知详情
    @staticmethod
    def get_user_notice_by_id(notice_id, user_id):
        notice_filter_data = MtUserMessage.objects.filter(id=int(notice_id), receiver_id=int(user_id))
        if notice_filter_data.exists():
            notice_data = notice_filter_data[0]
            notice_data.has_read = 1
            notice_data.save()

            return notice_data

        return None